package com.yndsoft.jc.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.yndsoft.jc.utils.VersionCheckInfo;
import com.yndsoft.jc.utils.VersionInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class STIDUtil {

    private static File file = new File(
            "data/data/com.lashou.cloud/file.xml");

    public static String getDeviceId(Context context) {
        String deviceId = "";
        try {
            deviceId = getIMIEStatus(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (deviceId == null || "".equals(deviceId) || "0".equals(deviceId)) {
            try {
                deviceId = getLocalMac(context).replace(":", "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (deviceId == null || "".equals(deviceId) || "0".equals(deviceId)) {
            try {
                deviceId = getAndroidId(context);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (deviceId == null || "".equals(deviceId) || "0".equals(deviceId)) {
            try {
                deviceId = read();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (deviceId == null || "".equals(deviceId) || "0".equals(deviceId)) {
                UUID uuid = UUID.randomUUID();
                deviceId = uuid.toString().replace("-", "");
                write(deviceId);
            }
        }
        return deviceId;
    }

    private static String replaceBlank(String mString) {
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        String str = mString;
        Matcher m = p.matcher(str);
        String after = m.replaceAll("");
        return after;
    }

    private static String getMacId(Context context) {
        String mac = "";
        try {
            mac = getLocalMac(context);
        } catch (Exception e) {

        }

        if (TextUtils.isEmpty(mac) || "0".equals(mac)) {
            try {
                mac = getAndroidId(context);
            } catch (Exception e) {

            }
        }

        return mac;
    }

    // IMEI码
    private static String getIMIEStatus(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = tm.getDeviceId();
        return deviceId;
    }

    // Mac地址
    private static String getLocalMac(Context context) {
        WifiManager wifi = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    // Mac地址
    private static String getAndroidId(Context context) {
        String androidId = Settings.Secure.getString(
                context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return androidId;
    }

    public static void write(String str) {
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Writer out = new OutputStreamWriter(fos, "UTF-8");
            out.write(str);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String read() {
        StringBuffer buffer = new StringBuffer();
        try {
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            Reader in = new BufferedReader(isr);
            int i;
            while ((i = in.read()) > -1) {
                buffer.append((char) i);
            }
            in.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getChannelIdByChannelName(String channelName) {
        String channelId = "10000";
        if ("qqappstore".equals(channelName)) {
            channelId = "10001";
        } else if ("baidu".equals(channelName)) {
            channelId = "10002";
        } else if ("huawei".equals(channelName)) {
            channelId = "10003";
        } else if ("qihu360".equals(channelName)) {
            channelId = "10004";
        } else if ("xiaomi".equals(channelName)) {
            channelId = "10005";
        } else if ("txls".equals(channelName)) {
            channelId = "10000";
        } else if ("anzhi".equals(channelName)) {
            channelId = "10006";
        } else if ("lianxiang".equals(channelName)) {
            channelId = "10007";
        } else if ("mumayi".equals(channelName)) {
            channelId = "10008";
        } else if ("qqshangdian".equals(channelName)) {
            channelId = "10009";
        } else if ("yingyonghui".equals(channelName)) {
            channelId = "10010";
        } else if ("oppo".equals(channelName)) {
            channelId = "10011";
        } else if ("wandoujia".equals(channelName)) {
            channelId = "10012";
        } else if ("sogou".equals(channelName)) {
            channelId = "10013";
        } else if ("leshi".equals(channelName)) {
            channelId = "10014";
        } else if ("meizu".equals(channelName)) {
            channelId = "10015";
        }
        return channelId;
    }

    public static String getSoftVersion(Context context) {
        PackageInfo info;
        try {
            info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return info.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "4.3";
        }
    }

    public static String getChannelId(Context context) {
        ApplicationInfo ai;
        try {
            ai = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            return getChannelIdByChannelName(ai.metaData
                    .getString("UMENG_CHANNEL"));
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "10062";
        }
    }

    public static String getSystemVersion() {
        return replaceBlank(android.os.Build.VERSION.RELEASE);
    }

    /**
     * 是否需要版本升级
     *
     * @param context
     * @param versionCheckInfo
     * @return
     */
    public static boolean needUpdate(Context context, VersionCheckInfo versionCheckInfo) {
        if (versionCheckInfo == null || context == null) {
            return false;
        }
        VersionInfo versionInfo = versionCheckInfo.getLatestVersion();
        if (versionInfo == null) {
            return false;
        }
        return !getSoftVersion(context).equals(versionInfo.getVersionName()) || versionCheckInfo.isForceUpgrade() || versionCheckInfo.isUpdateFlag();

    }

    public static boolean isOPPOPhone() {
//        OPPO手机有的不支持自定义notification
        return "oppo".equals(Build.BRAND.toLowerCase());
    }
}
